//
//  AVPlayerProvider.swift
//  Tiktok
//
//  Created by xmd on 11/2/20.
//

import Foundation
import AVKit

class AVPlayerProvider : ObservableObject {
    @Published var players: [Int: AVPlayer] = [:]
    
    func get(forPage index: Int, from url: String) -> AVPlayer? {
        if players[index] == nil {
            let avPlayer = AVPlayer(url: URL(string: url)!)
            NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: avPlayer.currentItem, queue: .main) { _ in
                avPlayer.seek(to: CMTime.zero)
                avPlayer.play()
            }
            players[index] = avPlayer
        }
        
        return players[index]
    }
}
